//
//  ThemeVCReactor.swift
//  WanAndroidLearn
//
//  Created by TRS-Mobile on 2023/11/2.
//

import Foundation
import ReactorKit
import RxCocoa
import RxSwift

class ThemeVCReactor: Reactor {
    
    enum Action {
        case refresh
        case selection(theme: ThemeCellReactor)
    }
    
    enum Mutation {
        case allColorThemes([ThemeCellReactor])
        case updateColorTheme(ThemeCellReactor)
    }
    
    struct State {
        var items: [ThemeCellReactor] = []
        var selected: ThemeCellReactor
    }
    
    var initialState: State = State(selected: ThemeCellReactor(themeColor: .red))
    
    func mutate(action: Action) -> Observable<Mutation> {
        switch action {
        case .refresh:
            return Observable.of(ColorTheme.allCases)
                .map { $0.map { ThemeCellReactor(themeColor: $0)} }
                .map { Mutation.allColorThemes($0) }
        case .selection(let theme):
            return Observable.just(.updateColorTheme(theme))
        }
    }
    
    func reduce(state: State, mutation: Mutation) -> State {
        var state = state
        switch mutation {
        case .allColorThemes(let array):
            state.items = array
        case .updateColorTheme(let themeCellReactor):
            let color = themeCellReactor.themeColor
            let theme = ThemeType.currentTheme()
                .withColor(color: color)
            themeService.switch(theme)
            state.selected = themeCellReactor
        }
        return state
    }
}
